package start.doubudouyin.utils;

import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class IconRead {
    // 默认存储目录
    private static final String DEFAULT_STORAGE_DIR = "D:\\Practice Project\\icon";
    // 图片大小限制(10MB)
    private static final double MAX_ICON_SIZE_MB = 10.0;

    // 配置参数，通过setter方法设置
    private static String contextPath = "/";
    @Setter
    private static int port = 8080;

    // 私有构造函数，防止实例化
    private IconRead() {}

    // 设置配置参数的静态方法
    public static void setContextPath(String path) {
        if (path != null) {
            contextPath = path;
        }
    }

    public static IconProcessResult processIconFile(MultipartFile file) throws IOException {
        return processIconFile(file, DEFAULT_STORAGE_DIR);
    }

    public static String generateIconUrl(String storedFileName) {
        // 处理contextPath，移除多余斜杠
        String contextPathTrimmed = contextPath.trim();
        contextPathTrimmed = contextPathTrimmed.replaceAll("//", "/");
        if (contextPathTrimmed.startsWith("/")) {
            contextPathTrimmed = contextPathTrimmed.substring(1);
        }
        if (contextPathTrimmed.endsWith("/")) {
            contextPathTrimmed = contextPathTrimmed.substring(0, contextPathTrimmed.length() - 1);
        }

        // 拼接标准URL
        StringBuilder urlBuilder = new StringBuilder("http://localhost:");
        urlBuilder.append(port);

        if (!contextPathTrimmed.isEmpty()) {
            urlBuilder.append("/").append(contextPathTrimmed);
        }

        urlBuilder.append("/icon/").append(storedFileName);
        return urlBuilder.toString();
    }

    public static IconProcessResult processIconFile(MultipartFile file, String targetDir)
            throws IOException {
        // 验证文件是否为空
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传的头像文件为空");
        }

        // 创建目标目录（如果不存在）
        Path targetPath = Paths.get(targetDir);
        if (!Files.exists(targetPath)) {
            Files.createDirectories(targetPath);
        }

        // 生成唯一文件名
        String fileName = file.getOriginalFilename();
        String uniqueFileName = generateUniqueFileName(fileName);
        File targetFile = new File(targetDir, uniqueFileName);

        // 保存文件
        try {
            file.transferTo(targetFile);

            // 检查图片大小
            double iconSize = getIconSize(targetFile.getAbsolutePath());
            if (iconSize > MAX_ICON_SIZE_MB) {
                boolean deleted = targetFile.delete();
                if (!deleted) {
                    throw new IOException("删除临时文件失败: " + targetFile.getAbsolutePath());
                }
                throw new IllegalArgumentException("头像大小超过10MB限制");
            }

            // 返回处理结果
            return new IconProcessResult(
                    uniqueFileName,
                    file.getOriginalFilename(),
                    file.getSize(),
                    file.getContentType(),
                    iconSize        // 大小（MB）
            );
        } catch (Exception e) {
            // 处理失败时删除已创建的文件
            if (targetFile.exists()) {
                boolean deleted = targetFile.delete();
                if (!deleted) {
                    throw new IOException("删除临时文件失败: " + targetFile.getAbsolutePath());
                }
            }
            throw new IOException("头像处理失败: " + e.getMessage(), e);
        }
    }

    private static String generateUniqueFileName(String originalFileName) {
        String extension = getFileExtension(originalFileName);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid + (extension.isEmpty() ? "" : "." + extension);
    }

    private static String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public record IconProcessResult(
            String storedFileName,
            String originalFileName,
            long fileSize,
            String contentType,
            double iconSizeMB        // 图片大小（MB）
    ) {}

    public static double getIconSize(String filePath) {
        File iconFile = new File(filePath);
        return (double) iconFile.length() / (1024 * 1024);
    }
}